from flask import Blueprint, request, jsonify
from app.models import User, ImageRecord
from app.models.score import Score
from app.utils import JwtToken

record_bp = Blueprint('record', __name__)


@record_bp.route('/api/image-records', methods=['GET'])
def get_image_records():
    # 1. 从请求头里拿 Bearer Token
    auth_header = request.headers.get("Authorization", None)
    if not auth_header or not auth_header.startswith("Bearer "):
        return jsonify({'code': 401, 'msg': '缺少或无效的 token'}), 401

    token = auth_header.split(" ")[1]

    # 2. 解析 token 获取 openid
    payload, verify_status = JwtToken.parse_token(token)
    if not verify_status or "openid" not in payload:
        return jsonify({'code': 401, 'msg': 'token 无效或过期'}), 401

    openid = payload["openid"]
    if not openid:
        return jsonify({'code': 400, 'msg': 'Missing openid'}), 400

    user = User.query.filter_by(openid=openid).first()
    if not user:
        return jsonify({'code': 404, 'msg': 'User not found'}), 404

    records = ImageRecord.query.filter_by(user_id=user.id).order_by(ImageRecord.created_at.desc()).all()
    return jsonify({
        'code': 200,
        'msg': 'Success',
        'data': [record.to_dict() for record in records]
    })


@record_bp.route('/api/exam-records', methods=['GET'])
def get_exam_records():
    # 1. 从请求头里拿 Bearer Token
    auth_header = request.headers.get("Authorization", None)
    if not auth_header or not auth_header.startswith("Bearer "):
        return jsonify({'code': 401, 'msg': '缺少或无效的 token'}), 401

    token = auth_header.split(" ")[1]

    # 2. 解析 token 获取 openid
    payload, verify_status = JwtToken.parse_token(token)
    if not verify_status or "openid" not in payload:
        return jsonify({'code': 401, 'msg': 'token 无效或过期'}), 401

    openid = payload["openid"]
    if not openid:
        return jsonify({'code': 400, 'msg': 'Missing openid'}), 400

    user = User.query.filter_by(openid=openid).first()
    if not user:
        return jsonify({'code': 404, 'msg': 'User not found'}), 404

    # 4. 查找考试记录
    records = Score.query.filter_by(openid=user.openid).order_by(Score.created_at.desc()).all()

    return jsonify({
        'code': 200,
        'msg': 'Success',
        'data': [
            {
                "score": record.score,
                "exam_time": record.created_at.strftime("%Y-%m-%d %H:%M:%S")
            }
            for record in records
        ]
    })
